import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { getSongsUrl, getLyric } from '@/api'
export const usePlayer = defineStore('player', () => {

  // audio dom 


  const musicList = ref([]); //  歌曲列表

  const currentIndex = ref(0); //  索引 


  const randomMusicList = ref([])
  const randomMusicIndex = ref(0)

  //  当前播放的歌曲  
  const currentMusic = ref({})


  watch(currentMusic, (count, prev) => {
    if (count.id !== prev.id) {

      if (!count.url) {
        // 数据变化了  
        getSongsUrl([count.mid]).then(res => {

          count.url = res.result[count.mid]

        })
      }

      if (!count.Lyric) {
        // 数据变化了  
        getLyric(count.mid).then(res => {
          let lyric = res.result.lyric;//  字符串
          let lyricArr = []
          lyric.split('\n').forEach(v => {

            let [time, word] = v.split(']')

            if (word) {
              time = time.slice(1)

              let [m, s] = time.split(':')



              lyricArr.push({
                time: Number(m) * 60 * 1000 + Number(s) * 1000,
                word
              })
            }

          })
          count.Lyric = lyricArr

        })
      }

    }

  })




  function addSong(item) {

    if (musicList.value.length === 0) {
      currentMusic.value = item
      musicList.value.push(item)
    } else {
      currentIndex.value++
      musicList.value.splice(currentIndex.value, 0, item)
      currentMusic.value = item
    }

  }

  return { musicList, addSong, currentMusic, currentIndex, randomMusicList, randomMusicIndex }

})
